﻿namespace LS.Nc6.Web.Entry.Areas.Systems.Controllers
{
    [Route("[area]/[controller]/[action]")]
    [Area("Systems")]
    [ApiDescriptionSettings("Default")]
    public class NoticeController : BaseAdminController
    {
        private readonly ISysNoticeService _noticeService;
        private readonly ISysUserService _userService;
        private readonly ICache _cache;
       
        public NoticeController(ISysNoticeService noticeService, ISysUserService userService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            : base(cacheOptions, resolveNamed)
        {
            _noticeService = noticeService;
            _userService = userService; 
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }

        #region 页面
        public ActionResult Index()
        {
            return View();
        }
        public async Task<ActionResult> EditNotice(long id)
        {
            SysPower(SysMenuConstant.MENU_NOTICE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = await _noticeService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            ViewBag.UserTransfer = JsonSerializer.Serialize( await GetUserTransfer(),CommonMethodHelper.MyJsonOptions);
            return View("EditNotice", model);
        }
        public  async Task<ActionResult> CreateNotice()
        {
            SysPower(SysMenuConstant.MENU_NOTICE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = new SysNoticeEntity();
            model.PublicTime = DateTime.Now;
            model.Status = 1;
            ViewBag.UserTransfer = JsonSerializer.Serialize(await GetUserTransfer(), CommonMethodHelper.MyJsonOptions);
            return View("EditNotice", model);
        }


        public async Task<ActionResult> Info(long id)
        {
            var model = await _noticeService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            //更改已读状态
            await _noticeService.SetNoticeToReads(id.ToString(), UserInfo.ID);
            return View(model);
        }
        #endregion


        #region 公共方法
        [HttpGet]
        public async Task<ResponseResultDataList> GetList()
        {
            string content = RequestHelper.FilterParam(Request.Query["content"]);
            string createtime = RequestHelper.FilterParam(Request.Query["createtime"]);
            var notifytype = Request.Query["notifytype"].ToString();
            var status = Request.Query["status"].ToString();
            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];
            var expable = Expressionable.Create<SysNoticeEntity>();
            expable.AndIF(!string.IsNullOrEmpty(notifytype),a=>a.NoticType == notifytype.ParseToInt());
            expable.AndIF(!string.IsNullOrEmpty(status), a => a.Status == status.ParseToInt());
            expable.AndIF(!string.IsNullOrEmpty(content), a => a.Content.Contains(content));
           
            if (!string.IsNullOrEmpty(createtime))
            {
                var ls = RequestHelper.GetDateForStr(createtime);
                if (ls.Count >= 2)
                {
                   
                    expable.And(a => a.CreateDate> ls[0].ParseToDateTime() && a.CreateDate <= (ls[1] + " 23:59:59").ParseToDateTime());
                }
            }
            var exp = expable.ToExpression();

            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<SysNoticeEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = a => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = a => new { a.CreateDate };
            }
           
            //var result = await _noticeService.PageList(exp, page, limit, expressionOrder,a=>new SysNoticeEntity { });
            var result = await _noticeService.PageDynamicList(exp, page, limit,true, expressionOrder, a => new  { id=a.Id, noticType=a.NoticType, publicTime=a.PublicTime, 
                publicUserName=a.PublicUserName, status=a.Status,title=a.Title });
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Item1, count = result.Item2 };
        }
       
        [HttpPost]
        public async Task<ResponseResult> DelNotice([FromBody] DeletDataInput input)
        {
            var result = await _noticeService.DeleteAsync(input.Ids);
            return ResponseHelper.DeleteResult(result);
        }

        [HttpPost]
        public async Task<ResponseResult> SetNoticeRead([FromBody] NoticeReadInput input)
        {
            await _noticeService.SetNoticeToReads(input.Ids, UserInfo.ID);

            return ResponseHelper.OperateResult(1);
        }
       

        /// <summary>
        /// 保存通知消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveNotice([FromBody]SysNoticeEntity model)
        {
            bool power = true;
            if ( string.IsNullOrEmpty(model.Content))
            {

                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_NOTICEEMPTY);
            }
            List<SysNoticeUserEntity> list = new List<SysNoticeUserEntity>();
            long result = 0;
            if (model.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_NOTICE_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel = await _noticeService.GetByIdAsync(model.Id);
                if (editmodel == null || editmodel.IsDeleted == 1)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.OPERATE_SJYSC);
                }
             
                CommonMethodHelper.MapperToModel(editmodel, model, null);
                if (model.UserList != null && model.UserList.Length > 0)
                {
                    for (int i = 0; i < model.UserList.Length; i++)
                    {
                        list.Add(new SysNoticeUserEntity
                        {
                            ReadStatus = 0,
                            UserId = model.UserList[i]
                        });
                    }
                }
                editmodel.PublicUserId = UserInfo.ID;
                editmodel.PublicUserName = UserInfo.RealName;
                result = await _noticeService.UpdateNotice(editmodel, list);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_NOTICE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                if (model.UserList != null && model.UserList.Length > 0)
                {
                    for (int i = 0; i < model.UserList.Length; i++)
                    {
                        list.Add(new SysNoticeUserEntity
                        {
                            ReadStatus = 0,
                            UserId = model.UserList[i]
                        });
                    }
                }
                model.PublicUserId = UserInfo.ID;
                model.PublicUserName = UserInfo.RealName;
                result = await _noticeService.InsertNotice(model, list);
            }
            return ResponseHelper.SaveResult(result);
           
        }
        #endregion

        #region 私有方法
        

        private async  Task<List<Hashtable>> GetUserTransfer()
        {
            List<Hashtable> list = new List<Hashtable>();
            var result = await _userService.List(a => true, a => a.Id);
            foreach (var item in result)
            {
                Hashtable hs = new Hashtable();
                hs.Add("value", item.Id);
                hs.Add("title",item.RealName+"["+item.UserName+"]");
                hs.Add("disabled","");
                hs.Add("checked","");
                list.Add(hs);
            }
            return list;
        }
        #endregion
    }
}